<template>
  <div class="create-wrapper">
    <h2 class="title">商标注册智能助理</h2>
    <!-- 聊天内容区域 -->
    <div ref="chatContent" class="chat-content">
      <div
        v-for="(message, index) in messages"
        :key="index"
        class="message-wrapper"
        :class="{ 'my-message-wrapper': message.isMine }"
      >
        <!-- 添加机器人头像 -->
        <div v-if="!message.isMine" class="avatar">
          <img src="@/assets/robot-avatar.png" alt="Robot Avatar" />
        </div>
        <div
          class="message"
          :class="{ 'my-message': message.isMine }"
          v-html="message.text"
        />
      </div>
    </div>
    <!-- 输入框区域 -->
    <div class="input-wrapper">
      <input
        v-model="newMessage"
        type="text"
        placeholder="输入您的要求..."
        @keydown.enter="sendMessage"
      />
      <button @click="sendMessage">发送</button>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick } from "vue";
import MarkdownIt from "markdown-it"; // 引入 markdown-it 库
// import axios from "axios"; // 引入 markdown-it 库
import { SSE } from "sse.js";

const messages = ref([]);
const newMessage = ref("");
const isLoading = ref(false);
// const currentResponse = ref("");
const chatContent = ref(null);
const markdownIt = new MarkdownIt(); // 初始化 markdown-it

// 从 localStorage 中读取消息
onMounted(() => {
  const savedMessages = localStorage.getItem("chatMessages");
  if (savedMessages) {
    messages.value = JSON.parse(savedMessages);
  }
  nextTick(() => {
    scrollToBottom(); // 确保 DOM 更新后再滚动到底部
  });
});

const scrollToBottom = () => {
  if (chatContent.value) {
    chatContent.value.scrollTop = chatContent.value.scrollHeight;
  }
};

const streamChat = async message => {
  try {
    messages.value.push({ text: "", isMine: false });
    await nextTick(); // 确保 DOM 更新完成后再滚动
    scrollToBottom();

    // const eventSource = new EventSource(`http://localhost:8000/call-session`);
    const source = new SSE("http://localhost:8000/call-session", {
      headers: { "Content-Type": "application/json" },
      method: "POST",
      payload: JSON.stringify({
        prompt: message
      })
    });
    source.addEventListener("open", function (e) {
      scrollToBottom();
    });

    source.addEventListener("done", function (e) {
      scrollToBottom();
    });
    source.addEventListener("message", function (event) {
      try {
        const jsonStr = event.data.trimEnd();
        const parsedResponse = markdownIt.render(jsonStr);
        const lastMessageIndex = messages.value.length - 1;
        if (lastMessageIndex >= 0) {
          messages.value[lastMessageIndex].text =
            messages.value[lastMessageIndex].text + parsedResponse;
        }
        scrollToBottom();
      } catch (e) {
        console.error("解析错误:", e);
      }
    });
    source.stream();
    // eventSource.addEventListener("done", () => {
    //   debugger;
    //   eventSource.close();
    //   isLoading.value = false;
    // });
  } catch (error) {
    console.error("请求错误:", error);
  } finally {
    isLoading.value = false;
  }
};

const sendMessage = async () => {
  if (newMessage.value.trim() && !isLoading.value) {
    const userMessage = newMessage.value;
    messages.value.push({ text: userMessage, isMine: true });
    newMessage.value = "";
    isLoading.value = true;
    await streamChat(userMessage);
    // 将消息保存到 localStorage
    localStorage.setItem("chatMessages", JSON.stringify(messages.value));
    // 发送消息后滚动到底部
    scrollToBottom();
  }
};
</script>

<style lang="css" scoped>
.add-spec-wrapper {
  display: flex;
  flex-direction: row;
  justify-content: flex-end;
  margin-bottom: 10px;
}

.create-wrapper {
  display: flex;
  flex-direction: column;
  height: calc(100vh - 100px);
  /* 使页面充满视口高度 */
  padding: 0px;
  overflow-y: auto;

  .create-wrapper h1 {
    font-size: 28px;
    color: #2c3e50;
    margin: 20px 0;
    text-align: center;
    font-weight: 600;
    letter-spacing: 1px;
    transition: all 0.3s ease;
    padding-bottom: 15px;
    border-bottom: 2px solid #007bff;
    position: relative;
  }

  .create-wrapper h1:after {
    content: "";
    position: absolute;
    bottom: -2px;
    left: 50%;
    width: 100px;
    height: 2px;
    background: #007bff;
    transform: translateX(-50%);
    transition: width 0.3s ease;
  }

  .create-wrapper h1:hover:after {
    width: 200px;
  }
}

.title {
  padding: 8px;
}

.footer-wrapper {
  width: 160px;
  margin: 0 auto;
  display: flex;
  flex-direction: row;
  justify-content: space-around;
}

.spec-section {
  border-bottom: 1px #ccc;
}

:deep(.el-card) {
  margin-bottom: 10px;
}

:deep(.el-divider--horizontal) {
  margin: 8px 0;
}

.footer {
  width: 100%;
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: space-evenly;
}

.chat-content {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
  background-color: #f9f9f9;
  border-radius: 8px;
  margin-bottom: 10px;
}

.message-wrapper {
  display: flex;
  align-items: flex-start;
  margin: 10px 0;
  width: 100%;
}

.avatar {
  width: 40px;
  height: 40px;
  margin-right: 10px;
}

.avatar img {
  width: 100%;
  height: 100%;
  border-radius: 50%;
}

.my-message-wrapper {
  justify-content: flex-end;
}

.message {
  padding: 12px 16px;
  background-color: #fff;
  border-radius: 12px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  max-width: 70%;
  word-wrap: break-word;
  overflow-wrap: break-word;
  /* 确保长单词或 URL 能够正确换行 */
  white-space: pre-wrap;
  /* 保留空白符并允许换行 */
}

.my-message {
  background-color: #007bff;
  color: #fff;
}

.input-wrapper {
  display: flex;
  padding: 10px;
  border-top: 1px solid #ccc;
  background-color: #fff;
  border-radius: 8px;
}

.input-wrapper input {
  flex: 1;
  margin-right: 10px;
  padding: 10px;
  border: 1px solid #ccc;
  border-radius: 8px;
}

.input-wrapper button {
  padding: 10px 20px;
  border: none;
  background-color: #007bff;
  color: #fff;
  border-radius: 8px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.input-wrapper button:hover {
  background-color: #0056b3;
}

:deep(.language-json) {
  overflow-wrap: break-word;
  white-space: pre-wrap;
}
</style>
